package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.adapter.HomePageListViewAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.CollectEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.fragment.BaseFragment;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

/**
 * 最新书列表
 * 
 * @author wangjian
 */
public class NewBookListActivity extends BaseActivity {

	private PullToRefreshListView choose_listview;
	private HomePageListViewAdapter adapter;
	private ArrayList<BookBean> bookList = new ArrayList<BookBean>();
	private int bookTypeId = -1;

	private View lvProductFooter;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;

	private int pageIndex = 0;

	private Handle handle = new Handle(NewBookListActivity.this) {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				String bottom = "";
				ResponeResult result = (ResponeResult) msg.obj;
				ArrayList<BookBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<BookBean>>() {}.getType());
				/**
				 * 把书缓存到本地
				 */
				Cache.cacheChoosePageList2Local(resultList);
				if (pageIndex == 0) {
					bookList.clear();
					bookList.addAll(resultList);
				} else {
					bookList.addAll(resultList);
				}
				if (resultList.size() >= 10) {
					pageIndex++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				} else {
					bottom = getResources().getString(
							R.string.text_hompage_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}

				if (choose_listview != null) {
					choose_listview.onRefreshComplete();
					choose_listview.setTag(0);
				}
				if (bookList != null && bookList.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				if (choose_listview != null) {
					choose_listview.onRefreshComplete();
					choose_listview.setTag(0);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				CommonMethod.makeNotice(NewBookListActivity.this, "登录成功");
				ResponeResult login_result = (ResponeResult) msg.obj;
				if(login_result != null){
					EventBus.getEventBus("login_success_refreshUI").post(login_result);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(NewBookListActivity.this, msg.obj.toString());
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_booklist_activity);
		initView();
		registerEvent();
	}

	@Subscribe
	public void onEventCollectSuccess(CollectEvent event) {
		if (bookList != null && bookList.size() > 0) {
			for (int i = 0; i < bookList.size(); i++) {
				if (event.getBookId() == bookList.get(i).getBookId()) {
					bookList.get(i).setIsFavor(event.isCollect() ? 2 : 1);
				}
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}

	public void registerEvent() {
//		EventBus.getEventBus(HttpRequestHelper.COLLECT_EVENT, ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
	}

	public void unregisterEvent() {
//		EventBus.getEventBus(HttpRequestHelper.COLLECT_EVENT, ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterEvent();
	}

	private void initView() {
		setTitle("最新");
		lvProductFooter = getLayoutInflater().inflate(R.layout.listview_footer,null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);

		choose_listview = (PullToRefreshListView) findViewById(R.id.choose_listview);
		adapter = new HomePageListViewAdapter(NewBookListActivity.this, bookList);
		choose_listview.setAdapter(adapter);
		choose_listview.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData();
			}
		});

		choose_listview.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData();
			}
		});
		choose_listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				choose_listview.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_hompage_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = Integer.parseInt((choose_listview.getTag()
						.toString()));
				if (scrollEnd && lvDataState == 0) {
					choose_listview.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = choose_listview.getCount() - 2; // 减去ListView的头和尾的
					getData();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				choose_listview.onScroll(view, firstVisibleItem,visibleItemCount, totalItemCount);
			}
		});
		choose_listview.clickRefresh();
	}

	public void notifyUI() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(NewBookListActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handle);
				}
			});
		}else if (requestCode == 100 && resultCode == 204) {
			EventBus.getEventBus("login_refreshUI").post(new LoginSuccessEvent());
		}
	}


	private void getData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(NewBookListActivity.this,HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(NewBookListActivity.this,HttpRequestHelper.NEWEST_BOOK, params, handle,HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}


	public void refreshUI() {
		if (choose_listview != null) {
			pageIndex = 0;
			choose_listview.clickRefresh();
		}
	}
}
